
package com.xg.gaud.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.xg.gaud.domain.SheetInfo;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedInputStream;
import java.io.InputStream;

/**
 * Excel 导出工具类
 * 支持模板导出，适用于多 Sheet 场景
 */
public class ExportUtil {

    /**
     * 多个 sheet 模板导出工具方法（支持本地路径导出）
     *
     * @param templateName 模板文件名
     * @param fullPath 导出文件的本地保存路径和文件名（如 "C:/exports/测试模板导出.xlsx"）
     * @param sheetInfo  sheet 的信息列表
     */
    public static void multiSheetTemplateUtil(String templateName, String fullPath, SheetInfo sheetInfo) {
        System.out.println("导出文件的本地保存路径和文件名:" + fullPath);
        InputStream templateStream = null;
        ExcelWriter excelWriter = null;

        try {
            String templatePath = "/export/" + templateName;
            ClassPathResource resource = new ClassPathResource(templatePath);

            if (!resource.exists()) {
                showAlert("错误：模板文件不存在，路径为：" + templatePath);
                return ;
            }

            templateStream = new BufferedInputStream(resource.getInputStream());
            excelWriter = EasyExcel.write(fullPath)
                    .withTemplate(templateStream)
                    .build();

            FillConfig fillConfig = FillConfig.builder().forceNewRow(true).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(sheetInfo.getSheetName()).build();

            if (sheetInfo.getDataList() != null && !sheetInfo.getDataList().isEmpty()) {
                excelWriter.fill(sheetInfo.getDataList(), fillConfig, writeSheet);
            }

            if (sheetInfo.getOtherData() != null && !sheetInfo.getOtherData().isEmpty()) {
                excelWriter.fill(sheetInfo.getOtherData(), writeSheet);
            }

            excelWriter.finish();
            String finalFullPath = fullPath;
            Platform.runLater(() -> showSuccessAlert(finalFullPath));

        } catch (Exception e) {
            String errMsg = "导出异常: " + e.getMessage();
            e.printStackTrace();
            Platform.runLater(() -> showAlert(errMsg));
        } finally {
            try {
                if (excelWriter != null) {
                    excelWriter.finish();
                }
                if (templateStream != null){
                    templateStream.close();
                }
            } catch (Exception ignored) {}
        }
    }

    private static void showAlert(String message) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("导出失败");
            alert.setHeaderText(null);
            alert.setContentText(message);
            alert.showAndWait();
        });
    }

    private static void showSuccessAlert(String filePath) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("导出成功");
            alert.setHeaderText(null);
            alert.setContentText("文件已成功导出至:\n" + filePath);
            alert.showAndWait();
        });
    }
}